/**
 * Copyright [2020] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.gateway.exec.handler;

import com.hyts.gateway.exec.listener.RouteRefreshPublisher;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @project-name:gateway
 * @package-name:com.hyts.gateway.exec.handler
 * @author:LiBo/Alex
 * @create-date:2020-12-20 20:00
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Service
public final class DynamicRouteDaoHandler implements RouteDataDaoSupport{


    final RouteRefreshPublisher routeRefreshPublisher;


    final RouteDefinitionRepository routeDefinitionRepository;


//    final RouteDefinitionRouteLocator routeDefinitionRouteLocator;

    /**
     * 新增插入
     * @param routeDefinition
     * @return
     */
    @Override
    public boolean insert(RouteDefinition routeDefinition) {
        try {
            routeDefinitionRepository.save(Mono.just(routeDefinition)).subscribe();
            routeRefreshPublisher.getApplicationEventPublisher().
                    publishEvent(new RefreshRoutesEvent(this));
        } catch (Exception e) {
            log.error("插入新增数据失败！",e);
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    /**
     * 更新数据
     * @param routeDefinition
     * @return
     */
    @Override
    public boolean update(RouteDefinition routeDefinition) {
        try {
            boolean result =  delete(routeDefinition);
            routeDefinitionRepository.save(Mono.just(routeDefinition)).subscribe();
            routeRefreshPublisher.getApplicationEventPublisher().
                    publishEvent(new RefreshRoutesEvent(this));
            return result;
        } catch (Exception e) {
            log.error("更新数据失败！",e);
            return Boolean.FALSE;
        }
    }

    /**
     * 删除数据
     * @param routeDefinition
     * @return
     */
    @Override
    public boolean delete(RouteDefinition routeDefinition) {
        try {
            this.routeDefinitionRepository.delete(Mono.just(routeDefinition.getId()))
                    .then(Mono.defer(() -> Mono.just(ResponseEntity.ok().build())
            )).onErrorResume((t) -> t instanceof NotFoundException,
                             (t) -> Mono.just(ResponseEntity.notFound().build())
            );
        } catch (Exception e) {
            log.error("删除数据失败！",e);
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }


    /**
     * 查询所有的相关服务信息
     * @return
     */
    @Override
    public Flux<RouteDefinition> query() {
        return routeDefinitionRepository.getRouteDefinitions();
    }
}
